package org.jim.server.helper;

import cn.hutool.core.collection.CollUtil;
import com.huiyun.project.common.core.constant.SecurityConstants;
import com.huiyun.project.common.core.util.fn.FunctionUtils;
import com.huiyun.project.im.entity.ImUser;
import com.huiyun.project.im.server.client.feign.RemoteUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jim.core.ImConst;
import org.jim.core.cache.redis.JedisTemplate;
import org.jim.core.cache.redis.RedisCacheManager;
import org.jim.core.packets.pub.pojo.JimUser;
import org.jim.core.packets.pub.consts.UserStatusType;
import org.jim.core.helper.IUserHelper;
import org.jim.core.utils.KeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @FileName: UserServiceImpl
 * @Description:
 * @Author linjie
 * @Date 2020/7/3010:53 AM
 * @Version 4.0.0
 */
@Component
@Slf4j
public class UserHelperImpl implements IUserHelper, ImConst {

    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 判断用户是否在线
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public boolean isOnline(String userId) {
        try {
            String keyPattern = KeyUtil.formatKey(USER_KEY.STATUS_GET, "userId", userId);
            Set<String> terminalKeys = JedisTemplate.me().keys(keyPattern);
            if (CollectionUtils.isEmpty(terminalKeys)) {
                return false;
            }
            Iterator<String> terminalKeyIterator = terminalKeys.iterator();
            while (terminalKeyIterator.hasNext()) {
                String terminalKey = terminalKeyIterator.next();
                terminalKey = terminalKey.substring(terminalKey.indexOf(userId));
                String isOnline = RedisCacheManager.getCache(USER).get(terminalKey, String.class);
                if (UserStatusType.ONLINE.getStatus().equals(isOnline)) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return false;
    }

    /**
     * 初始化用户在线状态;
     *
     * @param user
     */
    public boolean initUserStatus(JimUser user) {
        if (Objects.isNull(user) || Objects.isNull(user.getUsername())) {
            return false;
        }
        String userId = user.getUsername();
        boolean isOnline = this.isOnline(userId);
        if (isOnline) {
            user.setStatus(UserStatusType.ONLINE.getStatus());
        } else {
            user.setStatus(UserStatusType.OFFLINE.getStatus());
        }
        return true;
    }


    /**
     * 更新用户终端协议类型及在线状态;
     *
     * @param user 用户信息
     */
    @Override
    public boolean updateUserTerminal(JimUser user) {
        String userId = user.getUserId();
        String terminal = user.getTerminal();
        String status = user.getStatus();
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(terminal) || StringUtils.isEmpty(status)) {
            log.error("userId:{},terminal:{},status:{} must not null", userId, terminal, status);
            return false;
        }
        RedisCacheManager.getCache(USER).set(
                KeyUtil.formatKey(USER_KEY.STATUS_ADD,
                        "userId", userId,
                        "terminal", terminal),
                user.getStatus());
        return true;
    }


    @Override
    public JimUser getUserByType(String userId, Integer type) {
        //读取缓存中用户
        JimUser user = RedisCacheManager.getCache(USER).get(userId + SUFFIX + INFO, JimUser.class);
        if (Objects.isNull(user)) {
            return null;
        }
        //获取在线状态
        boolean isOnline = this.isOnline(userId);
        String status = isOnline ? UserStatusType.ONLINE.getStatus() : UserStatusType.OFFLINE.getStatus();
        //设置状态
        if (UserStatusType.ONLINE.getNumber() == type && isOnline) {
            user.setStatus(status);
            return user;
        } else if (UserStatusType.OFFLINE.getNumber() == type && !isOnline) {
            user.setStatus(status);
            return user;
        } else if (type == UserStatusType.ALL.getNumber()) {
            user.setStatus(status);
            return user;
        }
        return null;
    }

    /**
     * 获取在线agent
     * @param tenantId
     * @param orgId
     * @return
     */
    @Override
    public List<String> getOnlineCsList(String tenantId, String orgId) {
        try {
            List<ImUser> userList = FunctionUtils.getOkData(remoteUserService.getCsList(tenantId, orgId, SecurityConstants.FROM_IN));
            List<String> userIdList = new ArrayList<>();
            if (CollUtil.isNotEmpty(userList)) {
                for (ImUser user : userList) {
                    boolean isOnline = this.isOnline(user.getId());
                    if (isOnline) {
                        userIdList.add(user.getId());
                    }
                }

            }
            return userIdList;
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return null;

    }
}
